//
//  MJExamViewController.m
//  MJ
//
//  Created by lina on 2017/12/7.
//  Copyright © 2017年 lina. All rights reserved.
//

#import "MJExamViewController.h"
#import "MJQuestionsModel.h"
#import <YYKit.h>
#import "MJAnswerView.h"
#import "MJQuizzesViewModel.h"
#import "MJQuestionsModel.h"
#import "MJHomeModel.h"
#import "MJAnswerViewController.h"
#import "MJBackConfirmView.h"
#import "MJHomeViewController.h"

#define kMainColor [UIColor colorWithHexString:@"#2f9cd4"]

@interface MJExamViewController ()<MJQuestionsAnswerViewDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, strong) NSMutableArray <Problem *> *questionsArray;
@property (nonatomic, strong) NSMutableArray <Anwser *> *anwsersArray;



@property (nonatomic, strong) Problem *model;

@property (nonatomic, weak) UIScrollView *scrollView;
@property (nonatomic, weak) UILabel *questionlabel;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) BOOL isCreatControl;
@property (nonatomic, weak) MJAnswerView *answerView;

/** confirmView */
@property (nonatomic, strong) MJBackConfirmView *confirmView;


/**
 蒙版
 */
@property (nonatomic, strong) UIView *grayView;


@end

@implementation MJExamViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (NSMutableArray *)questionsArray
{
    if (!_questionsArray) {
        _questionsArray = [NSMutableArray array];
    }
    
    return _questionsArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //获取题目数据
    [self setQuestionsArray];
    self.navgationBar.titleLabel.text = self.quizzes.title;
    [self.navgationBar.leftNavigatoinItem addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];

}

- (void)back{
    
    [UIView animateWithDuration:.3 animations:^{
        
        self.grayView.alpha = .5;
        self.confirmView.centerY = self.view.centerY;
        
    }];
}

- (void)goBack{
    
    for (UIViewController *controller in self.navigationController.viewControllers) {
        
        if ([controller isKindOfClass:[MJHomeViewController class]]){
        
        [self.navigationController popToViewController:controller animated:YES];
        }
    }
}
- (void)cancel{
    
    [UIView animateWithDuration:.3 animations:^{
        self.confirmView.top = self.view.height;
        self.grayView.alpha = 0;

    }];
}

- (void)setQuestionsArray
{
    [MJQuizzesViewModel requestQuizzesDataWithID:self.quizzes.ID Success:^(MJQuestionsModel *questions) {
       
        self.questionsArray = [NSMutableArray arrayWithArray:[NSArray modelArrayWithClass:[Problem class] json:[questions.problem modelToJSONObject]]];
        self.anwsersArray = [NSMutableArray arrayWithArray:[NSArray modelArrayWithClass:[Anwser class] json:[questions.anwser modelToJSONObject]]];
        //获取题目信息，每次获取当前目标题目信息
        [self getQuestionsInfoWith:self.questionsArray[0]];

    } failure:^(NSError *error) {
    } netWorkState:^(BOOL netWorkState) {
    }];
}

//获取题目信息，每次获取当前目标题目信息
- (void)getQuestionsInfoWith:(Problem *)problem
{
    //更新模型
    _model = problem;
    //创建控件
    if (!_isCreatControl) [self creatControl];
    //刷新视图
    [self reloadView];
}

//创建控件
- (void)creatControl
{
    _isCreatControl = YES;
    
    //滚动视图
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.navgationBar.height, kScreenWidth, kScreenHeight - 113 - self.navgationBar.height)];
    scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:scrollView];
    self.scrollView = scrollView;
    
    //问题标签
    UILabel *questionLabel = [[UILabel alloc] init];
    questionLabel.textColor = [UIColor colorWithHexString:@"#666666"];
    questionLabel.font = [UIFont systemFontOfSize:20.];
    questionLabel.numberOfLines = 0;
    [scrollView addSubview:questionLabel];
    self.questionlabel = questionLabel;
    
    //答案选择视图，单选、多选、判断
    MJAnswerView *answerView = [[MJAnswerView alloc] init];
    answerView.delegate = self;
    [scrollView addSubview:answerView];
    self.answerView = answerView;
    
    [self.view addSubview:self.grayView];
    self.confirmView.frame = CGRectMake(20, kScreenHeight, kScreenWidth-40, 170);
    [self.view insertSubview:self.confirmView atIndex:999];

}

//刷新布局
- (void)reloadView
{
    //刷新问题相关数据
    NSString *questionlabelText = [NSString stringWithFormat:@"%@", _model.subtitle];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:4.0f];
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:20], NSParagraphStyleAttributeName:paragraphStyle};
    CGFloat questionLabelH = [questionlabelText boundingRectWithSize:CGSizeMake(kScreenWidth - 20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size.height;
    _questionlabel.text = questionlabelText;
    _questionlabel.backgroundColor = HEXColor(@"#f2f2f2");
    _questionlabel.frame = CGRectMake(20, 40, kScreenWidth - 20, questionLabelH);
    
    // 刷新答案相关数据
    [_answerView reloadViewWithFrame:CGRectMake(0, CGRectGetMaxY(_questionlabel.frame) + 18, kScreenWidth, 0) style:MJAnswerViewStyleSingleChoice answerArray:_model.choise];
}

#pragma mark - SXQuestionsFooterViewDelegate

-(void)questionsAnswerView:(MJAnswerView *)questionsAnswerView didClickOptionButton:(MJButton *)button{
    
    //获取目标题目信息
    if ([button.choise.to_act isEqualToString:@"problem"]) {
        Problem *nextProblem = self.questionsArray[[button.choise.to_val intValue] - 1];
        [self getQuestionsInfoWith:nextProblem];
    }else{
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
        });
        [self addProblem:button.choise.to_val];
        MJAnswerViewController *answerVc = [[MJAnswerViewController alloc] init];
        answerVc.anwser = self.anwsersArray[[button.choise.to_val intValue] - 1];
        answerVc.quizzes = self.quizzes;
        answerVc.quizzesArr = self.quizzesArr;
        answerVc.result = button.choise.to_val;
        [self.navigationController pushViewController:answerVc animated:YES];
    }
}

- (void)addProblem:(NSString *)answerIndex{
    
//    [MJQuizzesViewModel requestAddQuizzesDataWithProblemID:self.quizzes.ID Result:answerIndex Success:^(NSString *message) {
//        NSLog(@"add success!!");
//    } failure:^(NSError *error) {
//
//    } netWorkState:^(BOOL netWorkState) {
//
//    }];
    
    NSString *answer = [NSString stringWithFormat:@"%@-%@",self.quizzes.ID,answerIndex];
    NSArray * array = [[NSUserDefaults standardUserDefaults] arrayForKey:MJ_HistoryExams];
    if (array.count>0) {
        
        for (NSString *oldAnswer in array) {
            
            if (![answer isEqualToString:oldAnswer]) {
                
                NSMutableArray *examArray = [NSMutableArray arrayWithArray:array];
                [examArray addObject:answer];
                [[NSUserDefaults standardUserDefaults] setObject:examArray forKey:MJ_HistoryExams];
            }
        }
    }else{
        
        NSMutableArray *examArray = [NSMutableArray arrayWithArray:array];
        [examArray addObject:answer];
        [[NSUserDefaults standardUserDefaults] setObject:examArray forKey:MJ_HistoryExams];
    }
}

- (MJBackConfirmView *)confirmView{
    if (!_confirmView) {
        _confirmView = [[MJBackConfirmView alloc] init];
        ViewBorderRadius(_confirmView, 15, 0, [UIColor clearColor]);
        _confirmView.backgroundColor = [UIColor whiteColor];
        [_confirmView.comfirmButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
        [_confirmView.cancelButton addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmView;
}

- (UIView *)grayView{
    if (!_grayView) {
        _grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _grayView.backgroundColor = RGBColor(0, 0, 0);
        _grayView.alpha = 0;
    }
    return _grayView;
}

@end
